package edu.tsinghua.mrpvc.device.phone;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventHandler;
import org.osgi.util.tracker.ServiceTracker;

import edu.tsinghua.mrpvc.device.PhoneDevice;
import edu.tsinghua.mrpvc.device.simulate.PhoneSimulateTopic;


public class PhoneDeviceImpl implements PhoneDevice, EventHandler {

	ServiceTracker tracker;
	
	public PhoneDeviceImpl(BundleContext context){
		tracker = new ServiceTracker(context, EventAdmin.class.getName(), null);
		tracker.open();	
	}
	private void generDispatchEvent(String ID){
		EventAdmin eventAdmin = (EventAdmin) tracker.getService();
		if(eventAdmin != null){
			Map<String, String> proper = new Hashtable<String, String>();
			proper.put(PhoneDevice.EVENT_PROPER_PHONE_ID, ID);
			Event event = new Event(PhoneDevice.EVENT_TOPIC_DISPATCH, proper);
			eventAdmin.postEvent(event);
		}
	}
	@Override
	public int dispatch(String ID) {
		// TODO Auto-generated method stub
		System.out.println(Calendar.getInstance().getTime().toLocaleString() +
				" PhoneCenter: dispatch to " + ID + " executed");
		generDispatchEvent(ID);
		return 1;
	}
	
	private void generEvent(){
		EventAdmin eventAdmin = (EventAdmin) tracker.getService();
		if(eventAdmin != null){
			System.out.println(Calendar.getInstance().getTime().toLocaleString() + 
					" PhoneCenter: Someone is calling and post event");
			Map<String, String> property = new Hashtable<String, String>();
			Event event = new Event(PhoneDevice.EVENT_TOPIC_CALLING, property);
			eventAdmin.postEvent(event);
		}
	}
	
	public void ring(){
		generEvent();
	}
	
	public void over(){
		EventAdmin eventAdmin = (EventAdmin) tracker.getService();
		if(eventAdmin != null){
			Map<String, String> property = new Hashtable<String, String>();
			Event event = new Event(PhoneDevice.EVENT_TOPIC_OVER, property);
			eventAdmin.postEvent(event);
		}
	}

	@Override
	public String getID() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isValid() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public int setAutoTransMode() {
		// TODO Auto-generated method stub
		System.out.println(Calendar.getInstance().getTime().toLocaleString() + 
				"set AutoTransMode executed");
		return 1;
	}
	@Override
	public void handleEvent(Event event) {
		// TODO Auto-generated method stub
		if(event.getTopic().equals(PhoneSimulateTopic.PHONE_RING)){
			ring();
		}
		else if(event.getTopic().equals(PhoneSimulateTopic.PHONE_OVER)){
			over();
		}
	}

}
